package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.service.IOssUploadService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController

@RequestMapping("/api/upload")
public class UploadController {
    private static final String ALLOWED_EXTENSIONS = ".jpg,.jpeg,.png";


    @Value("${uploadFile.resourceHandler}")
    private String resourceHandler;//请求 url 中的资源映射，不推荐写死在代码中，最好提供可配置，如 /uploadFiles/**

    @Value("${uploadFile.location}")
    private String uploadFileLocation;//上传文件保存的本地目录，使用@Value获取全局配置文件中配置的属性值，如 E:/wmx/uploadFiles/

    @Autowired
    @Lazy
    IOssUploadService iOssUploadService;

    @Value("${aliyun.oss.showImgEndpoint}")
    String showImgEndpoint;

    /*
    @Value("${uploadFile.location}")
    private String uploadFileLocation;//上传文件保存的本地目录，使用@Value获取全局配置文件中配置的属性值，如 E:/wmx/uploadFiles/
    */

    @PostMapping("/uploadImage")
    public Result uploadImage(@RequestParam("file") MultipartFile appIcon) throws IOException {
        if (appIcon == null || appIcon.isEmpty()) {
            return new Result(Code.ERROR, null, "图片必须上传");
        }
        //获取上传文件的后缀名
        String fileSubName = Objects.requireNonNull(appIcon.getOriginalFilename()).substring(appIcon.getOriginalFilename().indexOf("."));
        if (!ALLOWED_EXTENSIONS.contains(fileSubName.substring(fileSubName.lastIndexOf(".")))) {
            return new Result(Code.ERROR, null, "图片不支持该类型，请上传图片");
        }

        Map<String, Object> mapResult = new HashMap<>();

        LocalDate localDate = LocalDate.now();
        String directoryName = "culitivate-images" + "/" + localDate.getYear() + "-" + localDate.getMonthValue();//应用图标目录

        String uploadUrl = uploadFileLocation + "/" + directoryName;
        File file = new File(uploadUrl);
        if (!file.exists()) {
            file.mkdirs();
        }

        String date = new SimpleDateFormat("yyyyMM").format(System.currentTimeMillis());
        String uuid = date + System.currentTimeMillis();
        String saveName = uuid + fileSubName;

        appIcon.transferTo(new File(uploadUrl, saveName));
        String filePath = uploadUrl + "/" + saveName;
        //上传到oss
        boolean ossUpRs = iOssUploadService.upFile(filePath, saveName, directoryName);

        String ossImageUrl;
        if (ossUpRs) {
            ossImageUrl = this.showImgEndpoint + "/" + directoryName + "/" + saveName;
            mapResult.put("picUrl", ossImageUrl);
        } else {
            return new Result(Code.ERROR, "上传图片失败，请重新上传");
        }

        return new Result(Code.OK, mapResult, "上传图片成功！");
    }
}
